package com.servoy.r3.tests;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;

public final class TestsUtils {

	public static Document getDocumentFromResource(String resourcename)
			throws Exception {
		DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dbuilder = dbfactory.newDocumentBuilder();

		InputStream stream = TestsUtils.class.getResourceAsStream(resourcename);

		Document xmldoc = dbuilder.parse(stream);

		return xmldoc;
	}

	public static Element getXmlElement(String element, String elementname,
			int index, boolean addroot) throws Exception {
		DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dbuilder = dbfactory.newDocumentBuilder();

		String text = "";

		if (addroot)
			text = "<root>" + element + "</root>";
		else {
			text = element;
		}

		byte bytes[] = text.getBytes();
		ByteArrayInputStream stream = new ByteArrayInputStream(bytes);

		Document xmldoc = dbuilder.parse(stream);
		Element root = xmldoc.getDocumentElement();

		if (!addroot && root.getTagName().equals(elementname))
			return root;

		NodeList nodes = xmldoc.getElementsByTagName(elementname);

		if (nodes.getLength() > 0 && nodes.getLength() > index) {
			Element el = (Element) nodes.item(index);

			return el;
		}

		return null;
	}

	public static String fillString(String text, String[] params) {
		String result = text;
		for (int i = 0; i < params.length; i++) {
			result = result.replaceAll("@" + i, params[i]);
		}

		return result;
	}
}
